import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import median_absolute_error,r2_score,max_error


data = pd.read_excel('home.xlsx')
# print(data.info())                        #查看是否存在缺失值
# data = data.dropna(how='any')             #利用dropna删除空白值所在行，any为删除存在空白值行
data["total_bedrooms"].fillna(data['total_bedrooms'].median,inplace=True)    #用中值填充空白值
# print(data.info())
# data.to_excel('home1.xlsx',sheet_name = 'home')

#特征矩阵分为两个
y = data['median_house_value']
X = data.drop("median_house_value",axis = 1)      #扔最后一列，axis = 1为按列扔
X = np.array(X)
y = np.array(y)

X_train,X_test,y_train,y_test = train_test_split (X,y,test_size = 0.15)
house = RandomForestClassifier(n_estimators=2)
house = house.fit(X_train,y_train)

sum0,sum1,sum2 = 0,0,0
ave0,ave1,ave2 = 0,0,0
for i in range(10):
    x = median_absolute_error(y_test,house.predict(X_test))    #计算预测误差的度量标准
    sum0 += x
    ave0 = sum0 / 10
    # print(x)
    y = r2_score(y_test,house.predict(X_test))                 #决定系数R的平方
    sum1 += y
    ave1 = sum1 / 10
    # print(y)
    z = max_error(y_test,house.predict(X_test))                #真实值和预测值之间最大误差
    sum2 += z
    ave2 = sum2 / 10 
print('median_absolute_error:',x)
print('r2_score:',y)
print('max_error:',z)
